package com.hosa.ai.robot.controller;

import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.deepseek.DeepSeekAssistantMessage;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @Author: hosa
 * @Date: 2025/9/30 15:34
 * @Version: v1.0.0
 * @Description: DeepSeek 聊天（R1 推理大模型）
 **/
@RestController
@RequestMapping("/v1/ai")
public class DeepSeekR1ChatController {

    @Resource
    private DeepSeekChatModel chatModel;

    /**
     * 流式对话
     * @param message
     * @return
     */
    @GetMapping(value = "/generateStream", produces = "text/html;charset=UTF-8")
    public Flux<String> generateStream(@RequestParam(value = "message",defaultValue = "你是谁？") String message) {
        //构建提示词
        Prompt prompt = new Prompt(new UserMessage(message));

        //流式输出
        return chatModel.stream(prompt)
                .mapNotNull(chatResponse ->{
                    //获取响应内容
                    DeepSeekAssistantMessage deepSeekAssistantMessage =
                            (DeepSeekAssistantMessage) chatResponse.getResult().getOutput();
                    //推理内容
                    String reasoningContent = deepSeekAssistantMessage.getReasoningContent();
                    //推理结束后的正式回答
                    String text = deepSeekAssistantMessage.getText();
                    //若有推理内容，响应推理内容，否则响应正式回答
                    String rawContent =StringUtils.isNotBlank(reasoningContent) ? reasoningContent : text;

                    // 将 \n 替换为 HTML 换行标签 <br>
                    return StringUtils.isNotBlank(rawContent) ? rawContent.replace("\n", "<br>") : rawContent;
                });

    }


}
